<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试记录查询</title>
    <script src="../public/exam/tailwindcss.min.js"></script>
    <link href="../public/exam/fontawesome.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        neutral: '#86909C'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {

            .card-shadow {
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            }

            .table-hover {
                @apply transition-colors hover:bg-gray-50;
            }
        }

        /* CSS计数器方式所需样式 */
        .counter-table {
            counter-reset: serial-number;
        }

        .counter-table td:first-child::before {
            counter-increment: serial-number;
            content: counter(serial-number);
        }

        @layer utilities {
            .dialog-backdrop {
                @apply fixed inset-0 bg-black/50 z-40 flex items-center justify-center opacity-0 pointer-events-none transition-opacity duration-300;
            }
            .dialog-backdrop.active {
                @apply opacity-100 pointer-events-auto;
            }
            .dialog-content {
                @apply bg-white rounded-lg shadow-xl w-full max-w-md mx-4 transform translate-y-8 opacity-0 transition-all duration-300;
            }
            .dialog-backdrop.active .dialog-content {
                @apply translate-y-0 opacity-100;
            }
            .dialog-header {
                @apply px-6 py-4 border-b border-gray-200 flex justify-between items-center;
            }
            .dialog-body {
                @apply px-6 py-4;
            }
            .dialog-footer {
                @apply px-6 py-4 border-t border-gray-200 flex justify-end gap-3;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-gray-800 min-h-screen">
<header class="bg-white border-b border-gray-200 sticky top-0 z-10">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">

        <!-- 左侧图片 -->
        <div class="flex items-center">
            <a href="#" class="flex items-center">
                <img src="../public/img/exam-logo.png" alt="网站Logo" style="width: 300px;height: 80px"
                     class="rounded-full object-cover">
                <span class="ml-3 text-xl font-bold text-gray-800"></span>
            </a>
        </div>

        <div class="flex items-center">
            <h1 class="text-lg font-semibold">考试记录列表</h1>
        </div>

        <div class="flex items-center gap-4">
            <button class="text-gray-500 hover:text-primary transition-colors">
                <i class="fa fa-bell-o"></i>
            </button>
            <div class="flex items-center gap-2">
                <span class="text-lg hidden sm:inline">全部数据</span>
            </div>
        </div>
    </div>
</header>

<main class="container mx-auto px-4 py-6">

    <!-- 搜索和筛选区域 -->
    <div class="bg-white rounded-lg p-4 mb-6 card-shadow">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">

            <div class="flex gap-3">
                <select id="basicSelect" class="flex-1 border border-gray-200 rounded-lg px-4 py-2 focus:outline-none focus:ring-2
                focus:ring-primary/30 focus:border-primary transition-all">
                    <option value="">全部校区</option>
                    <option value="CMP1">CMP1</option>
                    <option value="CMP3">CMP3</option>
                    <option value="CMP4">CMP4</option>
                    <option value="CMP7">CMP7</option>
                    <option value="CMP8">CMP8</option>
                    <option value="CMP9">CMP9</option>
                </select>
            </div>

            <div class="relative">
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                <input
                        type="text"
                        placeholder="搜索测试人..."
                        class="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none
                        focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all"
                        id="searchInput"
                >
            </div>

            <div class="flex gap-3">
                <select id="categorySelect"
                        class="flex-1 border border-gray-200 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                    <option value="">全部</option>
                    <option value="标准版">标准版</option>
                    <option value="挑战版">挑战版</option>
                </select>
            </div>

            <div class="flex gap-3">
                <div class="relative flex-1">
                    <i class="fa fa-calendar absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    <input id="basicDate"
                           type="date"
                           class="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all"
                    >
                </div>

                <button class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors flex items-center gap-1">
                    <i class="fa fa-filter"></i>
                    <span onclick="selectRecordList()">筛选</span>
                </button>
            </div>
        </div>
    </div>

    <!-- 考试记录列表 -->
    <div class="bg-white rounded-lg overflow-hidden card-shadow mb-6">
        <div class="overflow-x-auto">
            <table class="w-full counter-table">
                <thead>
                <tr class="bg-gray-50 border-b border-gray-200">
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 tracking-wider">记录编号</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        考试编号
                    </th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">校区</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">测试人
                    </th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        测试类别
                    </th>
                    <th class="px-6 py-3 w-[260px] text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        测试时间
                    </th>
                    <th style="display: none"
                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">得分
                    </th>
                    <th
                            class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态
                    </th>
                    <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">操作
                    </th>
                </tr>
                </thead>
                <tbody id="recordTableBody" class="divide-y divide-gray-200">
                <!-- 记录将通过JS动态生成 -->
                </tbody>
            </table>
        </div>

        <!-- 空状态 -->
        <div id="emptyState" class="py-16 text-center hidden">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                <i class="fa fa-file-text-o text-2xl text-gray-400"></i>
            </div>
            <h3 class="text-lg font-medium text-gray-900 mb-1">暂无考试记录</h3>
            <p class="text-gray-500 max-w-md mx-auto">没有找到符合条件的考试记录，请尝试调整筛选条件</p>
        </div>
    </div>
</main>

<!-- 考试详情模态框 -->
<div id="detailModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto mx-4 transform transition-all duration-300 scale-95 opacity-0"
         id="modalContent">
        <div class="p-6 border-b border-gray-200 flex justify-between items-center sticky top-0 bg-white z-10">
            <h3 class="text-lg font-bold text-gray-800" id="modalTitle">考试详情</h3>
            <button id="closeModal" class="text-gray-500 hover:text-gray-700">
                <i class="fa fa-times"></i>
            </button>
        </div>

        <div class="p-6" id="modalBody">
            <!-- 详情内容将通过JS动态生成 -->
        </div>
    </div>
</div>


<div id="detailArticle" class="dialog-backdrop">
    <div class="dialog-content">
        <div class="dialog-header">
            <h2 class="text-xl font-semibold text-primary flex items-center gap-2">
                <i class="fa fa-info-circle"></i>文章内容
            </h2>
            <button class="close-dialog text-gray-500 hover:text-gray-700">
                <i class="fa fa-times text-xl"></i>
            </button>
        </div>
        <div id="dialogBody" class="dialog-body">
            <p>这是一个信息对话框，用于向用户展示重要信息。它通常包含一些说明文本，帮助用户理解当前的操作或状态。</p>
        </div>
        <div class="dialog-footer">
            <input class="rounded pl-2" placeholder="请输入分数">
            <button class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded transition-colors">
                评分
            </button>
        </div>
    </div>
</div>

<script>
    // 考试记录数据
    let queryParams = {}
    let recordDetail = []
    let scoreMainId = ''  //需要评分的记录

    const basicSelect = document.getElementById('basicSelect');

    const categorySelect = document.getElementById('categorySelect');
    // 获取日期输入框元素
    const dateInput = document.getElementById('basicDate');

    basicSelect.addEventListener('change', function () {
        const selectedValue = this.value;
        if (selectedValue) {
            // let basicResultText = `值: "${selectedValue}", 文本: "${selectedText}"`;
            queryParams['campus'] = selectedValue
            // console.log(basicResultText);
        } else {
            queryParams['campus'] = null
        }
    });

    categorySelect.addEventListener('change', function () {
        const selectedValue = this.value;
        if (selectedValue) {
            // let basicResultText = `值: "${selectedValue}", 文本: "${selectedText}"`;
            queryParams['typeName'] = selectedValue
            // console.log(basicResultText);
        } else {
            queryParams['typeName'] = null
        }
    });

    // 绑定change事件
    dateInput.addEventListener('change', function () {
        // 获取选中的日期值 (YYYY-MM-DD 格式)
        const selectedDate = this.value;
        if (selectedDate) {
            // 显示结果
            // console.log('选中日期:', selectedDate);
            queryParams['date'] = selectedDate
        } else {
            queryParams['date'] = null
        }
    });

    // DOM元素
    const recordTableBody = document.getElementById('recordTableBody');
    const emptyState = document.getElementById('emptyState');
    const searchInput = document.getElementById('searchInput');
    const detailModal = document.getElementById('detailModal');
    const modalContent = document.getElementById('modalContent');
    const modalTitle = document.getElementById('modalTitle');
    const modalBody = document.getElementById('modalBody');
    const dialogBody = document.getElementById('dialogBody');
    const closeModal = document.getElementById('closeModal');

    const detailArticle = document.getElementById('detailArticle');
    const closeButtons = document.querySelectorAll('.close-dialog');
    // 渲染考试记录列表
    function renderExamRecords(records) {
        // 清空表格
        recordTableBody.innerHTML = '';

        // console.log(records);
        // 检查是否有记录
        if (records.length === 0) {
            emptyState.classList.remove('hidden');
            return;
        }

        // 隐藏空状态
        emptyState.classList.add('hidden');

        // 渲染每条记录
        records.forEach(record => {
            const row = document.createElement('tr');
            row.className = 'table-hover';

            // 状态样式
            let statusClass = '';
            let statusText = '';

            switch (record.score) {
                case 1:
                    statusClass = 'bg-success/10 text-success';
                    statusText = '已完成';
                    break;
                case 0:
                    statusClass = 'bg-warning/10 text-warning';
                    statusText = '待评分';
                    break;
            }

            row.innerHTML = `<td class="px-6 py-4 whitespace-nowrap"></td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="font-medium text-gray-900">${record._id}</div>
              </td>
               <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-gray-700">${record.campus}</span>
              </td>
               <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-gray-700">${record.user}</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-gray-700">${record.typeName}</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                <div class="text-xs">${record.time}</div>
              </td>
              <td style="display: none" class="px-6 py-4 whitespace-nowrap">
                <div class="font-medium text-success">
                  ${record.score}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 py-1 text-xs rounded-full ${statusClass}">
                  ${statusText}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
                <button
                    class="text-primary hover:text-primary/80 mr-3 putScore"
                    data-id="${record.practiceId}"
                >
                  评分
                </button>
                <button class="text-gray-500 hover:text-gray-700 view-detail">
                  查看
                </button>
              </td>
            `;

            recordTableBody.appendChild(row);
        });

        document.querySelectorAll('.putScore').forEach(btn => {
            btn.addEventListener('click', () => {
                showArticleDetail(btn.dataset.id);
            });
        });

        // 绑定查看详情事件
        document.querySelectorAll('.view-detail').forEach(btn => {
            btn.addEventListener('click', () => {
                showExamDetail(btn.dataset.id);
            });
        });
    }

    // 为所有关闭按钮添加事件监听器
    closeButtons.forEach(button => {
        button.addEventListener('click', () => {
            const dialog = button.closest('.dialog-backdrop');
            if (dialog) {
                closeDialog(dialog);
            }
        });
    });

    // 关闭对话框的函数
    function closeDialog(dialog) {
        dialog.classList.remove('active');
        document.body.style.overflow = ''; // 恢复背景滚动
    }

    async function showArticleDetail(id) {
        await fetchDataDetail(id)
        const article = recordDetail.filter(record => {return record.questionsText === 'article'})
        const articleElementElement = article[0]['userText'];
        scoreMainId = article[0]['_id'];
        console.log(scoreMainId);
        detailArticle.classList.add('active');
        document.body.style.overflow = 'hidden'; // 防止背景滚动
        dialogBody.innerHTML = articleElementElement;
        // console.log(detailArticle)
        // detailArticle.classList.remove('hidden');
        // setTimeout(() => {
        //     detailArticle.classList.remove('scale-95', 'opacity-0');
        //     detailArticle.classList.add('scale-100', 'opacity-100');
        // }, 100);
    }

    // 显示考试详情
    function showExamDetail(id) {
        fetchDataDetail(id)

        let record = recordDetail
        // if (record.length === 0) return;

        // 更新模态框标题
        // modalTitle.textContent = `${record.name} - 详情`;

        // 更新模态框内容
        modalBody.innerHTML = `
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">

        </div>
      `;

        // 显示模态框
        detailModal.classList.remove('hidden');
        setTimeout(() => {
            modalContent.classList.remove('scale-95', 'opacity-0');
            modalContent.classList.add('scale-100', 'opacity-100');
        }, 10);
    }

    // 关闭模态框
    function hideModal() {
        modalContent.classList.remove('scale-100', 'opacity-100');
        modalContent.classList.add('scale-95', 'opacity-0');

        setTimeout(() => {
            detailModal.classList.add('hidden');
        }, 300);
    }

    // 搜索测试人
    function handleSearch() {
        const searchTerm = searchInput.value.toLowerCase().trim();
        if (!searchTerm) {
            // 无搜索词，显示所有记录
            queryParams['user'] = null;
        } else {
            queryParams['user'] = searchTerm;
        }
    }

    // 绑定事件
    searchInput.addEventListener('blur', handleSearch);
    closeModal.addEventListener('click', hideModal);

    // 点击模态框背景关闭
    detailModal.addEventListener('click', (e) => {
        if (e.target === detailModal) {
            hideModal();
        }
    });

    function getRecordList() {
        // 2. 使用 URLSearchParams 构造参数（推荐，自动编码）
        const params = new URLSearchParams();
        params.append('pageSize', '10');
        params.append('pageNum', '1');
        fetchDataByParams(params)
    }

    function selectRecordList() {
        // 2. 使用 URLSearchParams 构造参数（推荐，自动编码）
        queryParams['pageNum'] = '1';
        // console.log(queryParams);
        const params = new URLSearchParams(queryParams);
        // console.log(params);
        // params.append('pageNum', '1');
        fetchDataByParams(params)
    }

    function fetchDataByParams(params) {
        // 创建请求头对象
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        fetch(`http://1.92.74.42:8088/comprehensive/page?${params.toString()}`, {
            method: 'GET', // 指定 方法
            headers: headers, // 传递请求头
            //body: JSON.stringify(userData) // 将数据转为 JSON 字符串
        }).then(response => {
            // console.log(response);
            return response.json();
        }).then(res => {
            // console.log(res);
            if (res.code === 200) {
                let records = res.rows;
                // console.log(records);
                renderExamRecords(records);
            }
            // 处理返回的数据
        }).catch(() => {
        });
    }

    async function fetchDataDetail(id) {
        // 创建请求头对象
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        await fetch(`http://1.92.74.42:8088/comprehensive/detail/` + id, {
            method: 'GET', // 指定 方法
            headers: headers, // 传递请求头
            //body: JSON.stringify(userData) // 将数据转为 JSON 字符串
        }).then(response => {
            console.log(response);
            return response.json();
        }).then(res => {
            console.log(res);
            if (res.code === 200) {
                recordDetail = res.data;
                // console.log(records);
                // console.log(records);
                // renderExamRecords(records);
            }
            // 处理返回的数据
        }).catch(() => {
        });
    }

    // 初始化页面
    window.addEventListener('DOMContentLoaded', () => {
        getRecordList();
    })
</script>
</body>
</html>
    